//
//  PlaybackViewController.m
//  GCDBenchmark
//
//  Created by Claude on 2025/10/23.
//

#import "PlaybackViewController.h"
#import "TestResultViewController.h"
#import "BenchmarkConfig.h"
#include "playback.h"

@interface PlaybackViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UITextField *sleepTextField;
@property (nonatomic, strong) UIButton *selectFileButton;
@property (nonatomic, strong) UIButton *runButton;
@property (nonatomic, strong) UILabel *selectedFileLabel;

@property (nonatomic, strong) NSString *selectedFilePath;
@property (nonatomic, strong) NSArray<NSString *> *playbackFiles;

@property (nonatomic, strong) TestResultViewController *resultVC;

@end

@implementation PlaybackViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor systemBackgroundColor];
    self.title = @"📹 Playback 测试";

    if (self.navigationController) {
        UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithTitle:@"关闭"
                                                                        style:UIBarButtonItemStylePlain
                                                                       target:self
                                                                       action:@selector(closeButtonTapped)];
        self.navigationItem.leftBarButtonItem = closeButton;
    }

    // 加载 playback 文件列表
    [self loadPlaybackFiles];

    // 加载上次保存的配置
    [self loadSavedConfig];

    // 设置UI
    [self setupUI];
}

#pragma mark - Actions

- (void)closeButtonTapped {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)loadPlaybackFiles {
    NSMutableArray *files = [NSMutableArray array];

    // 从 main bundle 中查找所有 .playback 文件
    NSArray *allResources = [[NSBundle mainBundle] pathsForResourcesOfType:@"playback" inDirectory:nil];

    for (NSString *path in allResources) {
        [files addObject:path];
    }

    self.playbackFiles = [files copy];
    NSLog(@"[DEBUG] Found %lu playback files", (unsigned long)self.playbackFiles.count);
}

- (void)loadSavedConfig {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    // 加载选中的文件
    NSString *savedFile = [defaults stringForKey:@"kPlaybackSelectedFile"];
    if (savedFile && [[NSFileManager defaultManager] fileExistsAtPath:savedFile]) {
        self.selectedFilePath = savedFile;
    }
}

- (void)setupUI {
    // 创建 TableView 作为容器
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleInsetGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.tableView];

    [NSLayoutConstraint activateConstraints:@[
        [self.tableView.topAnchor constraintEqualToAnchor:self.view.topAnchor],
        [self.tableView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.tableView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.tableView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
    ]];
}

#pragma mark - UITableView DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3; // Sleep 参数、文件选择、运行按钮
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) return 1; // Sleep 输入
    if (section == 1) return 1; // 文件选择
    if (section == 2) return 1; // 运行按钮
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        // Sleep 参数输入
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        UILabel *label = [[UILabel alloc] init];
        label.text = @"Sleep (秒):";
        label.translatesAutoresizingMaskIntoConstraints = NO;
        [cell.contentView addSubview:label];

        self.sleepTextField = [[UITextField alloc] init];
        self.sleepTextField.placeholder = @"0";
        self.sleepTextField.keyboardType = UIKeyboardTypeNumberPad;
        self.sleepTextField.borderStyle = UITextBorderStyleRoundedRect;
        self.sleepTextField.translatesAutoresizingMaskIntoConstraints = NO;

        NSInteger savedSleep = [[NSUserDefaults standardUserDefaults] integerForKey:@"kPlaybackSleepSeconds"];

        self.sleepTextField.text = [NSString stringWithFormat:@"%ld", (long)savedSleep];

        [cell.contentView addSubview:self.sleepTextField];

        [NSLayoutConstraint activateConstraints:@[
            [label.leadingAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor constant:16],
            [label.centerYAnchor constraintEqualToAnchor:cell.contentView.centerYAnchor],
            [label.widthAnchor constraintEqualToConstant:100],

            [self.sleepTextField.leadingAnchor constraintEqualToAnchor:label.trailingAnchor constant:8],
            [self.sleepTextField.trailingAnchor constraintEqualToAnchor:cell.contentView.trailingAnchor constant:-16],
            [self.sleepTextField.centerYAnchor constraintEqualToAnchor:cell.contentView.centerYAnchor],
            [self.sleepTextField.heightAnchor constraintEqualToConstant:36],
        ]];

        return cell;
    } else if (indexPath.section == 1) {
        // 文件选择
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];
        cell.textLabel.text = @"选择 Playback 文件";
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

        if (self.selectedFilePath) {
            cell.detailTextLabel.text = [self.selectedFilePath lastPathComponent];
            cell.detailTextLabel.textColor = [UIColor systemBlueColor];
        } else {
            cell.detailTextLabel.text = @"未选择";
            cell.detailTextLabel.textColor = [UIColor secondaryLabelColor];
        }

        return cell;
    } else {
        // 运行按钮
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        self.runButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [self.runButton setTitle:@"▶️  运行 Playback 测试" forState:UIControlStateNormal];
        self.runButton.titleLabel.font = [UIFont boldSystemFontOfSize:17];
        [self.runButton addTarget:self action:@selector(runPlaybackTest) forControlEvents:UIControlEventTouchUpInside];
        self.runButton.translatesAutoresizingMaskIntoConstraints = NO;
        [cell.contentView addSubview:self.runButton];

        [NSLayoutConstraint activateConstraints:@[
            [self.runButton.centerXAnchor constraintEqualToAnchor:cell.contentView.centerXAnchor],
            [self.runButton.centerYAnchor constraintEqualToAnchor:cell.contentView.centerYAnchor],
        ]];

        return cell;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) return @"⏱ 延迟参数";
    if (section == 1) return @"📁 文件选择";
    if (section == 2) return nil;
    return nil;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    if (section == 0) return @"设置运行前的等待时间（秒）";
    if (section == 1) return [NSString stringWithFormat:@"找到 %lu 个 playback 文件", (unsigned long)self.playbackFiles.count];
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

#pragma mark - UITableView Delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (indexPath.section == 1) {
        // 显示文件选择
        [self showFileSelectionAlert];
    }
}

#pragma mark - Actions

- (void)showFileSelectionAlert {
    if (self.playbackFiles.count == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"没有找到 Playback 文件"
                                                                       message:@"请确认项目中包含 .playback 文件"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"📹 选择 Playback 文件"
                                                                   message:@"请选择要运行的 playback 文件"
                                                            preferredStyle:UIAlertControllerStyleActionSheet];

    for (NSString *filePath in self.playbackFiles) {
        NSString *fileName = [filePath lastPathComponent];
        UIAlertAction *action = [UIAlertAction actionWithTitle:fileName
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction *action) {
            self.selectedFilePath = filePath;

            // 保存选择
            [[NSUserDefaults standardUserDefaults] setObject:filePath forKey:@"kPlaybackSelectedFile"];
            [[NSUserDefaults standardUserDefaults] synchronize];

            // 刷新界面
            [self.tableView reloadData];
        }];
        [alert addAction:action];
    }

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"
                                                           style:UIAlertActionStyleCancel
                                                         handler:nil];
    [alert addAction:cancelAction];

    // iPad 支持
    if (alert.popoverPresentationController) {
        alert.popoverPresentationController.sourceView = self.view;
        alert.popoverPresentationController.sourceRect = CGRectMake(self.view.bounds.size.width / 2,
                                                                      self.view.bounds.size.height / 2,
                                                                      1, 1);
    }

    [self presentViewController:alert animated:YES completion:nil];
}

- (void)runPlaybackTest {
    // 收起键盘
    [self.sleepTextField resignFirstResponder];

    // 验证参数
    if (!self.selectedFilePath || self.selectedFilePath.length == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"未选择文件"
                                                                       message:@"请先选择一个 playback 文件"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }

    NSInteger sleepSeconds = [self.sleepTextField.text integerValue];

    // 保存配置
    [[NSUserDefaults standardUserDefaults] setInteger:sleepSeconds forKey:@"kPlaybackSleepSeconds"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    // 创建并显示结果视图控制器
    self.resultVC = [[TestResultViewController alloc] init];
    self.resultVC.testName = @"Playback 测试";
    self.resultVC.testIcon = @"📹";
    self.resultVC.isRunning = YES;
    self.resultVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
    self.resultVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

    [self presentViewController:self.resultVC animated:YES completion:nil];

    // 在后台执行测试
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), ^{
        NSDate *startTime = [NSDate date];

        // 准备详细信息
        NSMutableString *detailInfo = [NSMutableString string];
        [detailInfo appendFormat:@"📊 测试配置\n"];
        [detailInfo appendFormat:@"━━━━━━━━━━━━━━━━━━━━\n"];
        [detailInfo appendFormat:@"Playback 文件: %@\n", [self.selectedFilePath lastPathComponent]];
        [detailInfo appendFormat:@"Sleep: %ld 秒\n\n", (long)sleepSeconds];
        [detailInfo appendFormat:@"⏱ 执行中...\n"];
        [detailInfo appendFormat:@"━━━━━━━━━━━━━━━━━━━━\n"];

        [self.resultVC updateProgress:detailInfo];

        // 执行测试
        NSLog(@"[DEBUG] Running playback from file: %@, sleep: %ld", self.selectedFilePath, (long)sleepSeconds);

        const char *cFilePath = [self.selectedFilePath UTF8String];
        run_playback(cFilePath, (size_t)sleepSeconds);

        NSLog(@"[DEBUG] Playback test completed");
        NSTimeInterval elapsed = [[NSDate date] timeIntervalSinceDate:startTime];

        // 构建最终结果
        NSMutableString *finalResult = [NSMutableString stringWithString:detailInfo];
        [finalResult appendFormat:@"\n✅ 测试完成\n"];
        [finalResult appendFormat:@"━━━━━━━━━━━━━━━━━━━━\n"];
        [finalResult appendFormat:@"总耗时: %.3f 秒\n", elapsed];

        [self.resultVC showResult:finalResult duration:elapsed];

        if ([BenchmarkConfig sharedConfig].autoExitEnabled) {
            dispatch_async(dispatch_get_main_queue(), ^{
                exit(0);
            });
        }
    });
}

@end
